package com.jielihaofeng.atguigu.nio;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Johnnie Wind
 * @description 应用实例1 - 本地文件写数据
 * @date 2021/11/25 11:25
 */
public class NioFileChannel01 {
    public static void main(String[] args) throws Exception {
        String str = "hello,借力好风";
        // 创建一个输出流
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");

        // 通过输出流获取文件channel
        // FileChannel 的真实类型是 FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();

        // 创建一个缓冲区ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put(str.getBytes());

        // 对byteBuffer进行flip
        byteBuffer.flip();

        // 将byteBuffer数据写入filechannel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();
    }
}
